package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    /**
     * 套餐分页查询
     *
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult queryPage(SetmealPageQueryDTO setmealPageQueryDTO) {
        //开启PageHelper分页
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());

        //调用mapper层查询
        List<SetmealVO> setmeal = setmealMapper.queryPage(setmealPageQueryDTO);
        Page<SetmealVO> total = (Page<SetmealVO>) setmeal;
        return new PageResult(total.getTotal(), setmeal);
    }

    /**
     * 新增套餐
     *
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void insertSetmeal(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        //设置时间和操作人
        setmeal.setCreateTime(LocalDateTime.now());
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setCreateUser(BaseContext.getCurrentId());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        //设置状态默认为0
        setmeal.setStatus(StatusConstant.DISABLE);
        //调用mapper层插入套餐基础数据
        setmealMapper.insertSetmeal(setmeal);
        //获取id
        Long id = setmeal.getId();
        // 设置套餐和菜品的关联关系
        // 获取套餐菜品列表
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        // 如果套餐菜品列表不为空，则批量插入套餐菜品关联数据
        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            for (SetmealDish setmealDish : setmealDishes) {
                setmealDish.setSetmealId(id);
            }
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    /**
     * 根据id查询套餐
     *
     * @param id
     * @return
     */
    @Override
    public SetmealVO getSetmealById(Long id) {

        return setmealMapper.getSetmealById(id);
    }

    /**
     * 修改套餐
     *
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void updateSetmeal(SetmealDTO setmealDTO) {
        //1.更新套餐基础数据
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        setmealMapper.updateSetmeal(setmeal);

        // 2. 先删除原有的套餐与菜品关联关系
        Long setmealId = setmealDTO.getId();
        setmealDishMapper.deleteBySetmealId(setmealId);
        //插入套餐菜品关联数据
        // 获取套餐菜品列表
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (setmealDishes != null && !setmealDishes.isEmpty()) {
            // 给每个关联关系设置套餐ID
            for (SetmealDish dish : setmealDishes) {
                dish.setSetmealId(setmealId);
            }
            setmealDishMapper.insertBatch(setmealDishes); // 批量插入
        }
    }

    /**
     * 更新套餐状态（起售/停售）
     *
     * @param status 状态值（1-起售，0-停售）
     * @param id    套餐ID列表
     */
    @Override
    @Transactional
    public void updateStatus(Integer status, Long id) {
// 启用套餐时，校验关联菜品是否均已起售（仅针对当前单个套餐）
        if (status == StatusConstant.ENABLE) {
            // 查询当前套餐关联的菜品ID
            List<Long> dishIds = setmealDishMapper.getDishIdsBySetmealId(id);
            if (dishIds != null && !dishIds.isEmpty()) {
                List<Dish> dishes = dishMapper.getByIds(dishIds);
                for (Dish dish : dishes) {
                    if (dish.getStatus() == StatusConstant.DISABLE) {
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                }
            }
        }
        // 构建单个套餐的更新对象
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();

        // 调用mapper更新单个套餐状态
        setmealMapper.updateStatus(setmeal);
    }

    /**
     * 批量删除套餐
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        // 1. 校验：是否包含起售状态的套餐，若有则禁止删除
        Integer count = setmealMapper.countByStatusAndIds(StatusConstant.ENABLE, ids);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }

        // 2. 删除套餐与菜品的关联关系（setmeal_dish表）
        setmealDishMapper.deleteBySetmealIds(ids);

        // 3. 删除套餐基础数据（setmeal表）
        setmealMapper.deleteBatch(ids);
    }


    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }
    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
}
